package com.learn.screw.generate;

import cn.smallbun.screw.core.Configuration;
import cn.smallbun.screw.core.engine.EngineConfig;
import cn.smallbun.screw.core.execute.DocumentationExecute;
import cn.smallbun.screw.core.process.ProcessConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;


/**
 * 数据库文档生成
 *
 * @author: MI
 * @email: 448341911@qq.com
 * @createTime: 2023/12/9 19:24
 * @updateUser: cong zhi
 * @updateTime: 2023/12/9 19:24
 * @updateRemark: 修改内容
 * @version: v1.0
 */
@Slf4j
@Component
public class GenerateDbDoc implements ApplicationRunner {

    @Autowired
    private ApplicationContext ctx;

    @Autowired
    private ScrewProperties screwProperties;

    @Autowired
    private DataSource dataSource;

    /**
     * 程序启动后执行
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        documentGeneration();
        // 安全关闭应用
        ((ConfigurableApplicationContext) ctx).close();
    }

    /**
     * 文档生成
     */
    private void documentGeneration() {
        // 生成配置
        EngineConfig engineConfig = EngineConfig.builder()
                .fileOutputDir(screwProperties.getFileOutputDir())
                .openOutputDir(screwProperties.getOpenOutputDir())
                .fileType(screwProperties.getFileType())
                .produceType(screwProperties.getProduceType())
                .fileName(screwProperties.getFileName())
                .build();

        // 指定生成逻辑、当存在指定表、指定表前缀、指定表后缀时，将生成指定表，其余表不生成、并跳过忽略表配置
        ProcessConfig processConfig = ProcessConfig.builder()
                .designatedTableName(screwProperties.getDesignatedTableName())
                .designatedTablePrefix(screwProperties.getDesignatedTablePrefix())
                .designatedTableSuffix(screwProperties.getDesignatedTableSuffix())
                .ignoreTableName(screwProperties.getIgnoreTableName())
                .ignoreTablePrefix(screwProperties.getIgnorePrefix())
                .ignoreTableSuffix(screwProperties.getIgnoreSuffix())
                .build();

        // 配置
        Configuration config = Configuration.builder()
                .version(screwProperties.getCommon().getVersion())
                .description(screwProperties.getCommon().getDescription())
                //数据源
                .dataSource(dataSource)
                //生成配置
                .engineConfig(engineConfig)
                //生成配置
                .produceConfig(processConfig)
                .build();
        //执行生成
        new DocumentationExecute(config).execute();
    }
}
